package com.lxl.bt.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.JsonObject;
import com.lxl.bt.Constant;
import com.lxl.bt.R;
import com.lxl.bt.activity.AboutUsActivity;
import com.lxl.bt.activity.BaseFragment;
import com.lxl.bt.activity.MessageListActivity;
import com.lxl.bt.activity.ProductDetailActivity;
import com.lxl.bt.activity.ProductListActivity;
import com.lxl.bt.activity.ShareActivity;
import com.lxl.bt.activity.WebviewActivity;
import com.lxl.bt.bean.A_Login;
import com.lxl.bt.bean.Banner;
import com.lxl.bt.bean.NearBox;
import com.lxl.bt.bean.NoticeBean;
import com.lxl.bt.bean.ProductBean;
import com.lxl.bt.net.NetApi;
import com.lxl.bt.net.Result;
import com.lxl.bt.retorfit.NetCallback;
import com.lxl.bt.retorfit.RetrofitUtil;
import com.lxl.bt.util.ACache;
import com.lxl.bt.util.GlideUtils;
import com.lxl.bt.util.Prefs;
import com.lxl.bt.view.CustomCommonDialog;
import com.stx.xhb.androidx.XBanner;
import com.sunfusheng.marqueeview.MarqueeView;
import com.yanzhenjie.sofia.Sofia;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static android.view.View.GONE;

/**
 * Create by lvxinlong
 * on 首页
 * on 2020年5月9日15:32:57
 **/
public class HomeFragment extends BaseFragment {


    @BindView(R.id.ivBack)
    ImageView ivBack;
    @BindView(R.id.txt_toolbar_title)
    TextView txtToolbarTitle;
    @BindView(R.id.rlBack)
    LinearLayout rlBack;
    @BindView(R.id.ivMessage)
    ImageView ivMessage;
    @BindView(R.id.tvMessageTag)
    TextView tvMessageTag;
    @BindView(R.id.rlRight)
    RelativeLayout rlRight;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.banner)
    XBanner banner;
    @BindView(R.id.ll1_1)
    LinearLayout ll11;
    @BindView(R.id.ll1_2)
    LinearLayout ll12;
    @BindView(R.id.ll1_3)
    LinearLayout ll13;
    @BindView(R.id.ll1_4)
    LinearLayout ll14;
    @BindView(R.id.ll2_1)
    LinearLayout ll21;
    @BindView(R.id.ll2_2)
    LinearLayout ll22;
    @BindView(R.id.ll2_3)
    LinearLayout ll23;
    @BindView(R.id.rcv)
    RecyclerView rcv;
    @BindView(R.id.ll3_1)
    LinearLayout ll31;
    @BindView(R.id.ll3_2)
    LinearLayout ll32;
    @BindView(R.id.tvMoreProduct)
    TextView tvMoreProduct;
    @BindView(R.id.tvGongGao)
    MarqueeView tvGongGao;
    private Unbinder unbinder;
    ACache aCache;
    private NearBox nearBox;
    private List<A_Login.MenuListBean.MenuChildrenBean> tabs = new ArrayList<>();
    private int current;
    A_Login a_login;
    private BaseQuickAdapter<ProductBean, BaseViewHolder> sysAdapter;
    private ArrayList<Banner> mBannerList ;

    public static HomeFragment newInstance() {
        Bundle bundle = new Bundle();
        HomeFragment fragment = new HomeFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_home, container, false);
//        ((BaseActivity) getActivity()).setStatusBarFullTransparent();

        //返回一个Unbinder值（进行解绑），注意这里的this不能使用getActivity()
        unbinder = ButterKnife.bind(this, view);
        aCache = ACache.get(getActivity());
        a_login = (A_Login) aCache.getAsObject(Constant.LOGIN);
        Sofia.with(getActivity())
                .invasionStatusBar()
                .statusBarBackgroundAlpha(0);
//                .statusBarLightFont();
//                .statusBarDarkFont()

        txtToolbarTitle.setText(Prefs.getStringValue(Constant.PHONE));
        initBanner();
        initNotices();
        getMessageTag();

        sysAdapter = new BaseQuickAdapter<ProductBean, BaseViewHolder>(R.layout.item_product) {
            @Override
            protected void convert(@NotNull BaseViewHolder baseViewHolder, ProductBean bean) {
            }


            @Override
            public void onBindViewHolder(@NonNull BaseViewHolder baseViewHolder, int position) {
                GlideUtils.loadImage(baseViewHolder.getView(R.id.ivBg), getItem(position).getBannerUrl());
                baseViewHolder.setText(R.id.tvTag, getItem(position).getCoinName());
                baseViewHolder.setText(R.id.tvtitle, getItem(position).getProductName());
                String value = getItem(position).getType().equals("1") ? "永久" : getItem(position).getDateLong() + "天期限";
                baseViewHolder.setText(R.id.tvtitleTag, value);
//                baseViewHolder.setText(R.id.tvDesc,getItem(position).);
                baseViewHolder.setText(R.id.tvPrice, getItem(position).getYearRate());

            }
        };
        rcv.setAdapter(sysAdapter);
        sysAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                startActivity(new Intent(getActivity(), ProductDetailActivity.class).putExtra("data", sysAdapter.getItem(position)));
            }
        });


        return view;
    }

    private void initNotices() {
        RetrofitUtil.getInstance().create(NetApi.class, 0)
                .tailgFeedBack().enqueue(new NetCallback<Result<ArrayList<NoticeBean>>>() {
            @Override
            public void onSuccess(Result<ArrayList<NoticeBean>> result) {
                if (result.isSuccess()) {
                    List<String> messages = new ArrayList<>();
                    for (NoticeBean notbean : result.getData()) {

                        messages.add(notbean.getContent());
                    }
                    tvGongGao.startWithList(messages);
                }
            }

            @Override
            public void netLogin() {

            }

            @Override
            public void onError(String errorStr) {
                super.onError(errorStr);
                Log.w("lxl", errorStr);

            }

        });
    }

    private void initBanner() {
        RetrofitUtil.getInstance().create(NetApi.class, 0)
                .homebannerList().enqueue(new NetCallback<Result<ArrayList<Banner>>>() {
            @Override
            public void onSuccess(Result<ArrayList<Banner>> result) {
                if (result.isSuccess()) {
                    mBannerList = result.getData();
                    banner.setBannerData(R.layout.layout_custom_view, mBannerList);
                }
            }

            @Override
            public void netLogin() {

            }

            @Override
            public void onError(String errorStr) {
                super.onError(errorStr);
                Log.w("lxl", errorStr);

            }

        });


//        data.add(new CustomViewsInfo("https://xcx.23ddc.com/image/lunbo/lunbo4.jpg"));
//        data.add(new CustomViewsInfo("https://xcx.23ddc.com/image/lunbo/lunbo4.jpg"));
//        data.add(new CustomViewsInfo("https://xcx.23ddc.com/image/lunbo/lunbo4.jpg"));
//        data.add(new CustomViewsInfo("https://xcx.23ddc.com/image/lunbo/lunbo4.jpg"));
//        banner.setBannerData(R.layout.layout_custom_view, data);
        banner.loadImage(new XBanner.XBannerAdapter() {
            @Override
            public void loadBanner(XBanner banner, Object model, View view, int position) {
                ImageView iv = (ImageView) view.findViewById(R.id.iv);
//                iv.setImageResource(R.mipmap.banner3);
                GlideUtils.loadImage(iv, (String) ((Banner) model).getXBannerUrl());
            }
        });
        banner.setOnItemClickListener((banner, model, view, position) -> {
            Banner bn = mBannerList.get(position);
            WebviewActivity.intent(getContext(),bn.getName(),bn.getUrl());
        });
    }


    @Override
    public void getData() {
        getList();
    }

    public void getList() {
        // 类型：0云矿机，1：实体矿机
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("pageNo", 1);
        jsonObject.addProperty("pageSize", 20);
        RetrofitUtil.getInstance().create(NetApi.class, 0)
                .product(0, 3, null, "", "").enqueue(new NetCallback<Result<ArrayList<ProductBean>>>() {
            @Override
            public void onSuccess(Result<ArrayList<ProductBean>> result) {
                if (result.isSuccess()) {
                    if (result.getData().size() > 3)
                        sysAdapter.setNewData(result.getData().subList(0, 3));
                    else {
                        sysAdapter.setNewData(result.getData());
                    }

                }
            }

            @Override
            public void netLogin() {

            }

            @Override
            public void onError(String errorStr) {
                super.onError(errorStr);
                Log.w("lxl", errorStr);

            }

        });
    }
    public void getMessageTag() {
        RetrofitUtil.getInstance().create(NetApi.class, 0)
                .pushMsgIsExistence().enqueue(new NetCallback<Result<Boolean>>() {
            @Override
            public void onSuccess(Result<Boolean> result) {
                if (result.isSuccess()) {// msg 1：显示星星 0：不显示星星
                    tvMessageTag.setVisibility("1".equals(result.getMsg())?View.VISIBLE:GONE);
                }else{
                    tvMessageTag.setVisibility(GONE);
                }
            }

            @Override
            public void netLogin() {
                tvMessageTag.setVisibility(GONE);
            }

            @Override
            public void onError(String errorStr) {
                super.onError(errorStr);
                Log.w("lxl", errorStr);
                tvMessageTag.setVisibility(GONE);
            }

        });
    }
    /**
     * onDestroyView中进行解绑操作
     */
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        if (a_login != null)
            tabs = a_login.menuList.get(0).getMenuChildren();
    }


    @OnClick({R.id.tvMoreProduct, R.id.rlBack, R.id.rlRight, R.id.banner, R.id.ll1_1,
            R.id.ll1_2, R.id.ll1_3, R.id.ll1_4, R.id.ll2_1,
            R.id.ll2_2, R.id.ll2_3, R.id.ll3_1, R.id.ll3_2,R.id.tv_more_platform})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rlBack:
                break;
            case R.id.rlRight:
                startActivity(new Intent(getActivity(), MessageListActivity.class));
                break;
            case R.id.banner:
                break;
            case R.id.ll1_1:
                startActivity(new Intent(getActivity(), ProductListActivity.class).putExtra("data", 0));
                break;
            case R.id.ll1_2:
                startActivity(new Intent(getActivity(), ProductListActivity.class).putExtra("data", 1));
                break;
            case R.id.tvMoreProduct:
                startActivity(new Intent(getActivity(), ProductListActivity.class));
                break;
            case R.id.ll1_3:
                startActivity(new Intent(getActivity(), ShareActivity.class));
                break;
            case R.id.ll1_4:
                //客服
                new CustomCommonDialog.Builder(getActivity(), false, true, true, Gravity.CENTER).serverDialog().show();
                break;
            case R.id.ll2_1:
                break;
            case R.id.ll2_2:
                break;
            case R.id.ll2_3:
                break;
            case R.id.ll3_1:
                break;
            case R.id.ll3_2:
                break;
            case R.id.tv_more_platform:
                startActivity(new Intent(getActivity(), AboutUsActivity.class));
                break;
        }
    }
}
